package com.shaoyu.elasticsearch.service;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.shaoyu.elasticsearch.pojo.SearchParam;
import com.shaoyu.elasticsearch.service.fulltext.FullTextSearchService;
import com.shaoyu.elasticsearch.service.fulltext.TermSearchService;
import com.shaoyu.elasticsearch.service.util.QueryBuilderUtil;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class ElasticsearchFullTextSearchServiceImpl implements FullTextSearchService {

    Logger logger = LoggerFactory.getLogger(ElasticsearchFullTextSearchServiceImpl.class);
    private Client client = ElasticSearchClientService.getNormalTransportClient();

    @Override
    public SearchResponse searchFullText(SearchParam param) {
        QueryBuilder queryBuilder = null;
        QueryBuilder postFilter = null;
        String checkResult = checkParam(param);
        if(StringUtils.isNotEmpty(checkResult)){
            logger.error("参数有误:"+checkResult);
            return null;
        }
        try{
            //初始化必要参数
            String[]indexArr = param.get("indexs").toString().split(",");
            String[]typeArr = param.get("types").toString().split(",");
            int from = Integer.parseInt(param.get("from").toString());
            int size = Integer.parseInt(param.get("size").toString());
            boolean explain = Boolean.parseBoolean(param.get("explain").toString());

            if(param.get("queryType")!=null){
                queryBuilder = QueryBuilderUtil.getQuery((Map<String,Object>)param.get("queryType"));
            }
            if(queryBuilder==null){
                logger.error("没有匹配到合适的查询方式:queryType:",param.get("queryType"));
                return null;
            }
            if(param.get("filter")!=null){
                postFilter = QueryBuilderUtil.getQuery((Map<String,Object>)param.get("filter"));
            }
            //设置查询参数
            SearchRequestBuilder builder = client.prepareSearch(indexArr)
                    .setTypes(typeArr).setQuery(queryBuilder);
            //设置过滤参数
            if (postFilter!=null){
                builder.setPostFilter(postFilter);
            }
            //查询
            return builder.setFrom(from).setSize(size).setExplain(explain).get();
        }catch (Exception e){
            logger.error("查询出错!ERROR:",e);
            return null;
        }
    }

    /**
     * 检查查询的几个必要参数
     * @param param
     * @return
     */
    private String checkParam(SearchParam param) {
        try{
            if(param.get("indexs")==null){
                return "参数indexs为空!";
            }else if (param.get("types")==null){
                return "参数types为空!";
            }
            if (param.get("from")==null){
                param.set("from",0);
            }
            if(param.get("size")==null){
                param.set("size",20);
            }
            if(param.get("explain")==null){
                param.set("explain",true);
            }
        }catch (Exception e){
            logger.error("检查参数出错:",e);
            return e.toString();
        }
        return null;
    }

}
